package com.ywb.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;

import java.util.Calendar;
import java.util.Map;

public class JWTUtils {

    /**
     * Token密钥,如果被别人拿到可能就token就有被破解的风险
     */
    private static final String SIGN = "!Q@W#E$R%T";

    /**
     * 生成token header.payload.signature
     * @param map
     * @return
     */
    public static String getToken(Map<String, String> map){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 3);

        JWTCreator.Builder builder = JWT.create();

        map.forEach((k,v) ->{
            builder.withClaim(k, v);
                });

        String token = builder.withExpiresAt(instance.getTime()) //指定令牌过期时间
                .sign(Algorithm.HMAC256(SIGN)); //sign

        return token;
    }

    /**
     * 验证Token
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

}
